
const rtcroom = require('./utils/rtcroom.js');
// 修改调整读取位置 支持授权发布模式 modify by cw 20181121
// const config = (JSON.stringify(wx.getExtConfigSync()) !== '{}' ? wx.getExtConfigSync() : require('../config.js')).config_trtc;
const { config: { config_trtc: config }} = require('../common/utils/ws/ws-config.js');
// 修改调整读取位置 支持授权发布模式 modify by cw 20181121
const { getUserInfo } = require('../common/utils/ws/wsxcx-opendata-sdk');
function getLoginInfo(options) {
  wx.login({
    success: function (res) {
      if (res.code) {
        options.code = res.code;
        getUserInfo().then(wsUserInfo => {  
          options.userName = wsUserInfo.nickName || '';
          proto_getLoginInfo(options);
        }).catch(res=>{  //这里失败不直接去授权页 因为考虑到用户体验，首次给空
          options.userName='';
          proto_getLoginInfo(options);
        });
      } else {
        console.log('获取用户登录态失败！' + res.errMsg);
        options.fail && options.fail({
          errCode: -1,
          errMsg: '获取用户登录态失败，请退出重试',
        });
      }
    },
    fail: function (res) {
      let errCode;
      let errMsg;
      console.log('获取用户登录态失败！' + res.errMsg);
      if (res.errMsg == 'request:fail timeout') {
        errCode = -1;
        errMsg = '网络请求超时，请检查网络状态';
      }
      options.fail && options.fail({
        errCode: errCode || -1,
        errMsg: errMsg || '获取用户登录态失败，请退出重试',
      });
    },
  });
}

// 调用后台获取登录信息接口
function proto_getLoginInfo(options) {
  wx.request({
    url: `${config.serverUrl}/weapp/utils/get_login_info?rtc_port=${config.port}`,
    data: { userIDPrefix: 'weixin', code: options.code },
    method: 'GET',
    header: {
      'content-type': 'application/json', // 默认值
    },
    success: function (ret) {
      if (ret.data.code) {
        console.log('获取登录信息失败，调试期间请点击右上角三个点按钮，选择打开调试');
        options.fail && options.fail({
          errCode: ret.data.code,
          errMsg: ret.data.message + '[' + ret.data.code + ']',
        });
        return;
      }
      console.log('获取IM登录信息成功: ', ret.data);
      ret.data.serverDomain = `${config.roomServiceUrl}/weapp/${options.type}/`;
      ret.data.userName = options.userName;
          rtcroom.login({
            data: ret.data,
            success: options.success,
            fail: options.fail,
          });
    },
    fail: function (ret) {
      let errCode;
      let errMsg;
      console.log('获取IM登录信息失败: ', ret);
      if (ret.errMsg == 'request:fail timeout') {
        errCode = -1;
        errMsg = '网络请求超时，请检查网络状态';
      }
      options.fail && options.fail({
        errCode: errCode || -1,
        errMsg: errMsg || '获取登录信息失败，调试期间请点击右上角三个点按钮，选择打开调试',
      });
    },
  });
}

module.exports = {
  getLoginInfo: getLoginInfo,
};
